<?php


namespace app\common\service;

// 处理业务

use app\common\model\Admin;
use app\common\model\Order as OrderModel;
use app\common\model\OrderExpress;
use plug\SUtil;
use plug\SConstant;
use plug\SHttp;
use plug\xpyun\model\PrintRequest;
use plug\xpyun\service\PrintService;
use plug\xpyun\util\NoteFormatter;
use think\facade\Config;


class ServiceAdmin extends ServiceBase
{
	
	function getAdmin($user_name){
		$adminModel = new Admin();
		$where = [
			'user_name'=>$user_name,
			'status'=>1,
		];
		// 查询用户所有信息
        $info = $adminModel->field('user_id')->where($where)->find();
        if(!$info){
            return [];
        }
		return $info->toArray();
	}

    // 以用户名查询 用户是否正确
    function Getuser_name ($user_name, $user_pass) {
        $adminModel = new Admin();

        $where = [
            'user_name'=>$user_name,
            'status'=>1,
        ];
        // 查询用户所有信息
        $userArr = $adminModel->getOne($where,'user_id,user_name,group_id,user_pass,pass_random,lock_note,status,spf_id,sbg_id');
        $password = SUtil::getHashBackend($user_pass, $userArr['pass_random']);
        if((!$userArr || ($password !== $userArr['user_pass']))){
            $this->setError(-1, "密码错误");
            return false;
        }elseif($userArr['status'] == 2){//密码匹配上了但是被锁定了
            //写入登录日志
            $this->setError(-1, '用户账号被锁定['.$userArr['lock_note'].']');
            return false;
        }else{
            //登录成功
            $pass_random = $this->update_login($userArr['user_id'],$user_pass);
            //写cookie
            $loginInfo = array(
                'admin_userid' => $userArr['user_id'],
                'admin_user_name' => $userArr['user_name'],
                'admin_spf_id' => $userArr['spf_id'],
                'admin_sbg_id' => $userArr['sbg_id'],
                'admin_userkey' => md5($userArr['user_id'] . $userArr['user_name'] . $userArr['group_id'] . SConstant::ADMINUSERKEY . $pass_random)
            );
            $expireTime = 3600 * 24 * 7;

            // 设置
            cookie('name', $loginInfo, $expireTime);
        }

        return true;
    }

    /**
     * 更新用户登录成功的信息
     */
    public function update_login($userid,$user_pass=''){
        $adminModel = new Admin();

        if(empty($userid)){
            return false;
        }
        $where = ['user_id' => $userid];

        $loginSucInfo = array(
            'last_time'=>time(),
            'last_ip'=>SUtil::getIp()
        );
        if($user_pass){
            $loginSucInfo['pass_random'] = SUtil::random(6,0);
            $loginSucInfo['user_pass'] = SUtil::getHashBackend($user_pass, $loginSucInfo['pass_random']);
        }
        $re = $adminModel->getUpdate($where, $loginSucInfo);
        if($re==false||!$loginSucInfo['pass_random']){//未更新成功或者未更新pass_random那么返回原来的sn
            $one = $adminModel->getOne($where,'pass_random');
            $loginSucInfo['pass_random'] = $one['pass_random'];
        }
        return $loginSucInfo['pass_random'];
    }

    // 处理添加管理用户
    public function DealAdmin($params)
    {
        $adminModel = new Admin();

        // 取出用户ID
        $user_id = $params['user_id'];
        // 去除数组中的user_id
        unset($params['user_id']);

        // 判断密码是否为空
        if(!empty($params['user_pass'])){
            $user_pass = $params['user_pass'];
        }else{
            // 默认密码
            $user_pass = "456789";
        }

        if(!empty($params['spf_id'])){
            $params['spf_id'] = $params['spf_id'];
        } else {
            $params['spf_id'] = '0';
        }

        // 密码随机验证码
        $params['pass_random'] = SUtil::random(6,0);
        // 生成密码
        $params['user_pass'] = SUtil::getHashBackend($user_pass, $params['pass_random']);
        // 创建时间戳
        $params['add_time'] = time();

        $rs = $adminModel->edit($params, $user_id);
        if($rs === false){
            $this->setError("-1",$adminModel->getError());
            return false;
        }
        return $rs;
    }

	/**
	 * 查询快递接口
	 * @param $orderId
	 * @return false|mixed
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function CheckExpress($orderId)
	{
		// 订单快递数据
		$orderModel = new OrderModel();
		$order_data = $orderModel->alias('o')->field('o.order_status,o.express_id,o.tracking_number,o.r_phone,e.express_name,e.express_code')->where(['order_id' => $orderId])->leftJoin([
			['ddt_express e','o.express_id=e.express_id'],
		])->find();
		if ($order_data['order_status'] != 3 && $order_data['order_status'] != 4) {
			$this->setError(-1,'未发货');
			return false;
		}

		$OrderExpress = new OrderExpress();
		$orderexpress_data = $OrderExpress->getOne(['order_id' => $orderId]);
		if($orderexpress_data && calculate([time(), $orderexpress_data['check_time']], '-') <= 3600){
			$result = json_decode($orderexpress_data['result'],true);
			return [
				'list'=>$result['data'],
				'message'=>$result['message'],
				'express_name'=>$order_data['express_name']
			];
		}

		//判断物流信息是否过期，过期就查询一边
		$key = 'PPouFJQR3601';                        // 客户授权key
		$customer = '5F6DBDD708A91FE1098353F80794B666';                   // 查询公司编号
		$param = array (
			'com' => $order_data['express_code'],             // 快递公司编码
			'num' => $order_data['tracking_number'],     // 快递单号
			'phone' => $order_data['r_phone'],                // 手机号
			'resultv2' => 1,
			'order' => 'desc'             // 返回结果排序:desc降序（默认）,asc 升序
		);

		//请求参数
		$post_data = [
			'customer'=>$customer,
			'param'=>json_encode($param)
		];
		//生成签名
		$sign = md5($post_data['param'].$key.$post_data['customer']);
		$post_data['sign'] = strtoupper($sign);
		$url = 'https://poll.kuaidi100.com/poll/query.do';    // 实时查询请求地址
		// 发送post请求
		$result = SHttp::http_curl($url,http_build_query($post_data),[],'post');
		$data = json_decode($result['str'],true);
		if($data['message'] != 'ok'){
			$this->setError(-1,$data['message']);
			return false;
		}

		if($orderexpress_data){
			$rs = $OrderExpress->save([
				'check_time'    => time(),
				'result'    => json_encode($data),
			],[
				'order_id'=>$orderId,
				'express_type'=>1,
			]);
			if(!$rs){
				$this->setError(-1,$OrderExpress->getError());
				return false;
			}
		}
		if(!$orderexpress_data){
			$rs = $OrderExpress->save([
				'order_id'    => $orderId,
				'check_time'    => time(),
				'result'    => json_encode($data),
			]);
			if(!$rs){
				$this->setError(-1,$OrderExpress->getError());
				return false;
			}
		}
		return [
			'list'=>$data['data'],
			'message'=>$data['message'],
			'express_name'=>$order_data['express_name']
		];
	}


	// 打印订单
	public function GetDevice($order, $type)
    {

        $request = new PrintRequest();
        $Service = new PrintService();
        $request->generateSign();
        $deviceConfig = Config::pull('device');

        if($type == 1){
            $request->sn = $deviceConfig['PrinterSN'];
        }elseif ($type == 2){
            $request->sn = $deviceConfig['PrinterSN2'];
        }

        //*必填*：打印内容,不能超过12K
        $request->content = $this->GetContent($order, $type);

        //打印份数，默认为1
        $request->copies = 1;

        //声音播放模式，0 为取消订单模式，1 为静音模式，2 为来单播放模式，3为有用户申请退单了。默认为 2 来单播放模式
        $request->voice = 2;
        //打印模式：
        //值为 0 或不指定则会检查打印机是否在线，如果不在线 则不生成打印订单，直接返回设备不在线状态码；如果在线则生成打印订单，并返回打印订单号。
        //值为 1不检查打印机是否在线，直接生成打印订单，并返回打印订单号。如果打印机不在线，订单将缓存在打印队列中，打印机正常在线时会自动打印。
        $request->mode = 1;

        $result = $Service->xpYunPrint($request);
    }


	/**
     * 生成设备打印内容
     */
	public function GetContent($order, $type)
    {
        $printContent = "";
//
////        $printContent = $printContent . "<C>" . "<B>".$order['shop_name'].".小票</B>" . "<BR></C>";
//        $printContent = $printContent . "<C>" . "<B>".$order['table']."</B>" . "<BR></C>";
//        $printContent = $printContent . "<BR>";
//
//        $printContent = $printContent . "菜名" . str_repeat(" ", 16) . "数量" . str_repeat(" ", 2) . "单价" . str_repeat(" ", 2)
//            . "<BR>";
//        $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
//
//        foreach ($order['detail'] as $key => $val){
//            $printContent  = $printContent . NoteFormatter::formatPrintOrderItem($val['product_name'], $val['quantity'], $val['sale_price']);
//        }
//
//
//        $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
//        $printContent = $printContent . "<R>" . "合计：" . $order['pay_amount'] . "元" . "<BR></R>";
//
//        $printContent = $printContent . "<BR>";
//        $printContent = $printContent . "<L>"
//            . "下单时间：" . date("Y-m-d H:i",$order['order_time']) . "<BR>"
//            . "备注：" . $order['remarks'] . "<BR>";
//        $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
//        $printContent = $printContent . "<C>" . "<B>".$order['shop_name'].".小票</B>" . "<BR></C>";
//        $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
//
//
//        if ($type == 1){
            // 柜台打单
//        $printContent = $printContent . "<C>" . "<B>".$order['shop_name'].".小票</B>" . "<BR></C>";
            $printContent = $printContent . "<C>" . "<B>".$order['table']."</B>" . "<BR></C>";

            $printContent = $printContent . "<C>" . "订单号：".$order['orderno'] . "<BR><BR></C>";
            $printContent = $printContent . "<BR>";

            $printContent = $printContent . "菜名" . str_repeat(" ", 16) . "数量" . str_repeat(" ", 2) . "单价" . str_repeat(" ", 2)
                . "<BR>";
            $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";

            foreach ($order['detail'] as $key => $val){
                $printContent = $printContent . NoteFormatter::formatPrintOrderItem($val['product_name'], $val['quantity'], $val['sale_price']);
            }


            $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
            $printContent = $printContent . "<R>" . "合计：" . $order['pay_amount'] . "元" . "<BR></R>";

            $printContent = $printContent . "<BR>";
            $printContent = $printContent . "<L>"
                . "下单时间：" . date("Y-m-d H:i",$order['order_time']) . "<BR>"
                . "备注：" . $order['remarks'] . "<BR>";
            $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
            $printContent = $printContent . "<C>" . "<B>".$order['shop_name'].".小票</B>" . "<BR></C>";
            $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
//        }elseif ($type == 2){
//            // 厨房打单
//            // 一个菜打一个单
//
////        $printContent = $printContent . "<C>" . "<B>".$order['shop_name'].".小票</B>" . "<BR></C>";
//            $printContent = $printContent . "<C>" . "<B>".$order['table']."</B>" . "<BR><BR></C>";
//            $printContent = $printContent . "<C>" . "订单号：".$order['orderno'] . "<BR></C>";
//            $printContent = $printContent . "<BR>";
//
//            $printContent = $printContent . "菜名" . str_repeat(" ", 16) . "数量" . str_repeat(" ", 2) . "<BR>";
//            $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
//
//            $printContent = $printContent . NoteFormatter::formatPrintOrderItem2($order['product_name'], $order['quantity']);
//
//
//
//            $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
////            $printContent = $printContent . "<R>" . "合计：" . $order['pay_amount'] . "元" . "<BR></R>";
//
//            $printContent = $printContent . "<BR>";
//            $printContent = $printContent . "<L>"
//                . "下单时间：" . date("Y-m-d H:i",$order['order_time']) . "<BR>"
//                . "备注：" . $order['remarks'] . "<BR>";
////            $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
////            $printContent = $printContent . "<C>" . "<B>".$order['shop_name'].".小票</B>" . "<BR></C>";
//            $printContent = $printContent . str_repeat("-", NoteFormatter::MAX_HEAD_NAME_CHAR_LEN80) . "<BR>";
//        }

        return $printContent;
    }






}